﻿
#region csMake3D, Copyright(C) 2008 Stefano Vena, Licensed under MIT License.
/*	csMake3D a library for making complex 3D objects
	Copyright (C) 2008
	Stefano Vena
	stefano.vena@gmail.com
	http://code.google.com/p/csmake3d/
    Version 0.0.1

The MIT License

Copyright (c) 2008 Stefano Vena

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion


using System;
using System.Collections.Generic;

namespace csMake3D.makers {
   public class SplineExtruder {       
        public core.Shape Section { get;set;}
        public Sharp3D.Math.Core.Vector3FArrayList Spline { get; set; }
        public List<float> Scale { get; set; }
        public List<float> Rotation { get; set; }


        public SplineExtruder() {
            Section = new core.Shape();
            Spline = new Sharp3D.Math.Core.Vector3FArrayList(10);
            Scale = new List<float>(10);
            Rotation = new List<float>(10);
        }



        private Sharp3D.Math.Core.Vector3F rotateAroundAxis(Sharp3D.Math.Core.Vector3F point, Sharp3D.Math.Core.Vector3F Axis, float angle) {            
                Sharp3D.Math.Core.QuaternionF q = new Sharp3D.Math.Core.QuaternionF(angle, Axis);
                Sharp3D.Math.Core.QuaternionF cq = q;
                cq.Inverse();                
                 
                Sharp3D.Math.Core.QuaternionF res = new Sharp3D.Math.Core.QuaternionF(0, point);
                res = q * res * cq;                     
                return  new Sharp3D.Math.Core.Vector3F(res.X, res.Y, res.Z);               
        }

        private void transformSection(Sharp3D.Math.Core.Vector3F A, Sharp3D.Math.Core.Vector3F B, Sharp3D.Math.Core.Vector3F C, ref Sharp3D.Math.Core.Vector3F Normal) {

                /*      Y
                 *      | 
                 *      |
                 *      |_______ X
                 *     /
                 *    /
                 *   Z
                 */

                Sharp3D.Math.Core.Vector3F from = Normal;
                Sharp3D.Math.Core.Vector3F to = (C - A);
                

                float xfrom = from.X;
                float yfrom = from.Y;
                float zfrom = from.Z;
                float xto = to.X;
                float yto = to.Y;
                float zto = to.Z;
                float d = xfrom * xto + yfrom * yto + zfrom * zto; //dot(from, to);
                float xq = yfrom * zto - yto * zfrom; // vector3 c = cross( from,to );
                float yq = zfrom * xto - zto * xfrom;
                float zq = xfrom * yto - xto * yfrom;
                float wq = (float)Math.Sqrt((xfrom * xfrom + yfrom * yfrom + zfrom * zfrom) * (xto * xto + yto * yto + zto * zto)) + d;
                if (wq < 0.0001) {
                    xq = -zfrom; // Cross.set( -UnitFrom.z, 0, UnitFrom.x );
                    yq = yfrom;
                    zq = xfrom;
                    wq = 0;
                }
                float cnorm = (float)Math.Sqrt(xq * xq + yq * yq + zq * zq + wq * wq);
                xq /= cnorm; // q.normalize();
                yq /= cnorm;
                zq /= cnorm;
                wq /= cnorm;


                Sharp3D.Math.Core.QuaternionF q = new Sharp3D.Math.Core.QuaternionF(wq, xq, yq, zq);
                Sharp3D.Math.Core.QuaternionF cq = q;
                cq.Inverse();

                foreach (csMake3D.core.Vertex v in this.Section) {

                    Sharp3D.Math.Core.QuaternionF res = new Sharp3D.Math.Core.QuaternionF(0, v.Pos);

                    res = q * res * cq;
                    v.Pos = new Sharp3D.Math.Core.Vector3F(res.X, res.Y, res.Z);                    
                }

                Section.Center = B;
                Normal = to;
                Normal.Normalize();
   }

        public core.Vertex[] getExtrusion() { return getExtrusion(0, Spline.Count); }       
        public core.Vertex[] getExtrusion(int from, int to) {


                core.InterpolatedArray<float> scale_v = (Scale.Count<2) ? null : new csMake3D.core.InterpolatedArray<float>(Spline.Count, Sharp3D.Math.Core.MathFunctions.CubicInterpolation, Scale);
                core.InterpolatedArray<float> rotate_v = (Rotation.Count < 2) ? null : new csMake3D.core.InterpolatedArray<float>(Spline.Count, Sharp3D.Math.Core.MathFunctions.CubicInterpolation, Rotation); 
                
                core.Vertex[] ex = new core.Vertex [( (to - from) * Section.Count ) + 2];
                Sharp3D.Math.Core.Vector3F a = Spline[from];
                Sharp3D.Math.Core.Vector3F b = Spline[from];
                Sharp3D.Math.Core.Vector3F c = Spline[from];
                Sharp3D.Math.Core.Vector3F Normal = Section.Normal;
                                           Normal.Normalize();
                float section_radius = this.Section.getRadius();
                int next_vertex = 0; 

                for (int i = from; i < to; i++) {
                    a = b;
                    b = c;

                    if (i == 0)
                        c = Spline[from+1];
                    else if (to - 1 == i)
                        c = Spline[i];
                    else
                        c = Spline[i + 1];
                    transformSection(a, b, c, ref Normal);
                                        
                    if (i == from ) {
                        ex[next_vertex] = new csMake3D.core.Vertex();
                        ex[next_vertex].Pos = a.Clone();
                        ex[next_vertex].Normal = -Normal;
                        next_vertex++;
                    }

                    for( int k = 0; k < Section.Count; k++ ){
                        core.Vertex v = ex[next_vertex] = Section[k].Clone();
                        v.Normal = v.Pos.Clone();
                        if (v.Normal.GetLengthSquared() != 0)
                            v.Normal.Normalize(); 
                        
                        if (rotate_v != null) {
                            v.Pos = rotateAroundAxis(v.Pos, Section.Normal, rotate_v[i]);
                        }
                        
                        v.Pos += Section.Center;

                        if (scale_v != null) {
                            v.Pos *= scale_v[i];                        
                        }
                        
                        v.TCoord = new Sharp3D.Math.Core.Vector2F((float)k / (float)(Section.Count - 1), (float)(i-from)/ (float)(to-from-1));
                        next_vertex++;
                    }

                    if ( i == to - 1) {
                        ex[next_vertex] = new csMake3D.core.Vertex();
                        ex[next_vertex].Pos = c.Clone();
                        ex[next_vertex].Normal = Normal;
                        next_vertex++;
                    }
                }
                return ex;
        }

        public int[] getIndices() { return getIndices(true, true); }
        public int[] getIndices(bool closeFront, bool closeBack) {
           int size = Spline.Count;

           int indices_size = Section.Count * (size - 1) * 6;
           if (closeFront) indices_size += (Section.Count) * 3;
           if (closeBack) indices_size += (Section.Count) * 3;

           int[] tubeIndices = new int[ indices_size ];
           int idx = 0;
           
           if (closeFront) {
               for (int j = 0; j < Section.Count; j++) {
                   tubeIndices[idx++] = (int)0;
                   tubeIndices[idx++] = 1+(((int)j + 1) % Section.Count);
                   tubeIndices[idx++] = 1+(((int)j) % Section.Count);
               }
           }

           for (int i = 1; i < size; i++) {
               int primo = (i - 1) * Section.Count;
               int secondo = i * Section.Count;

               for (int j = 0; j < Section.Count; j++) {
                   tubeIndices[idx++] = 1+(int)(primo + j);
                   tubeIndices[idx++] = 1+(int)(secondo + ((j + 1) % Section.Count));
                   tubeIndices[idx++] = 1+(int)(secondo + (j % Section.Count));

                   tubeIndices[idx++] = 1+(int)(primo + j);
                   tubeIndices[idx++] = 1+(int)(primo + ((j + 1) % Section.Count));
                   tubeIndices[idx++] = 1+(int)(secondo + ((j + 1) % Section.Count));
               }
           }
           if (closeBack) {
               int centro = 1 + (int)((size) * Section.Count);
               int zero = 1 + (int)((size - 1) * Section.Count);
               for (int j = 0; j < Section.Count; j++) {
                   
                   tubeIndices[idx++] = zero + (((int)j) % Section.Count);
                   tubeIndices[idx++] = zero + (((int)j + 1) % Section.Count);
                   tubeIndices[idx++] = (int)centro;
               }
           }

           return tubeIndices;

       }

        public void calcSmoothNormals(ref  core.Vertex[] ex) {
            int[] idx = getIndices();
            utils.helpers.NormalsMapping.calcSmoothNormals(ref ex, ref idx);
        }
        
   }
}
